package com.qf.common.event.publish;

import com.qf.common.event.utils.Contacts;
import com.qf.common.event.utils.EventMessage;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.utils.SerializationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 发布端的API对象
 */
@Component
public class EventSend {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 消息发送的方法
     * @param eventType
     * @param event
     * @param <T>
     */
    public <T> void send(String eventType, T event){

        //将开发者的实体进行过一次封装（事件实体、事件类型、事件ID....）
        EventMessage eventMessage = new EventMessage(eventType, event);

        //EventMessage -> byte[]
        byte[] body = SerializationUtils.serialize(eventMessage);

        //再将事件实体封装到RabbitMQ支持的实体中
        Message message = new Message(body, new MessageProperties());

        //调用RabbitMQ的模板对象，发送消息
        rabbitTemplate.send(Contacts.EXCHANGE_NAME, "", message);
    }
}
